# -*- coding: utf-8 -*-
'''
sftp获取远程服务器文件模块
@author LongTao 2023.06.01
'''
import paramiko as pm
import os, datetime


def sftp(ip,port,user,pwd,remote_path,local_path):

    # 建立SSH和SFTP连接
    ssh = pm.SSHClient()
    ssh.set_missing_host_key_policy(pm.AutoAddPolicy())
    ssh.connect(hostname=ip, port=port, username=user, password=pwd)
    sftp = ssh.open_sftp()

    # 获取SFTP服务器上最新的文件
    latest_file = max(sftp.listdir(remote_path), key=lambda f: sftp.stat(os.path.join(remote_path, f)).st_mtime)

    # 复制文件到本地服务器目标目录
    sftp.get(os.path.join(remote_path, latest_file), os.path.join(local_path, latest_file))

    # 关闭SFTP连接
    sftp.close()
    ssh.close()

    with open('/opt/rsdata/project/log.txt','a',encoding='utf-8') as f: # 简易log
        timenow = str(datetime.datetime.now())
        f.write(timenow + " 最新文件已获取，文件名: " + latest_file + '\n')

def run():
    ip = '10.205.136.129'
    port = 10022
    user = 'techuser'
    pwd = 'Tec.pw129'
    remote_dir = '/dev_kpi/'
    local_dir = '/opt/rsdata/file/'
    try:
        sftp(ip,port,user,pwd,remote_dir,local_dir) # 调用获取文件方法
    except:
        print('get newest file error')
